package com.sitia.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.sitia.common.CustomException;
import com.sitia.system.domain.SqlParams;
import com.sitia.system.mapper.SysSqlMapper;
import com.sitia.system.service.ISysSqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Service
public class SysSqlServiceImpl implements ISysSqlService {
    @Autowired
    private SysSqlMapper sysSqlMapper;
    @Override
    public List<Map<String, Object>> selectSql(SqlParams sql) {
        String replace;
        try {
            replace = java.net.URLDecoder.decode( sql.getSql(), "UTF-8" )
                    .replace( "\n", " " )
                    .replace( "\t", " " );
            sql.setSql(replace);
        } catch ( UnsupportedEncodingException e ) {
            throw new CustomException( "sql有误" );
        }
        PageHelper.startPage( sql.getPageNum(), sql.getPageSize() );
        List<Map<String, Object>> list = sysSqlMapper.selectSql(sql);
//        return jdbcTemplate.queryForList( replace );
        // 暂时不需要多数据源
        /*String dataSource = Optional.ofNullable(sql.getDataSource()).orElse(DbUtil.MASTER);
        List<Map<String, Object>> list = DynamicDatasourceUtils.dsInvoke(dataSource, () -> {
            return sysMenuMapper.selectSql(sql);
        });*/
        for(Map<String, Object> dataMap : list){
            if (dataMap == null) {
                continue;
            }
            for(String key : dataMap.keySet()){
                if(dataMap.get(key).getClass().toString().toUpperCase().indexOf("BLOB")>-1){
                    dataMap.put(key,"(大文本字段)");
                }

                if(dataMap.get(key).getClass().toString().toUpperCase().indexOf("CLOB")>-1){
                    dataMap.put(key,"(大文本字段)");
                }
            }
        }
        return list;
    }
}
